#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
from datetime import datetime
from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility
from extension.test_logic.RequestBase import RequestBase


class REDFISH_SESSION_001(Case):
    """
        Name:
            REDFISH_SESSION_001
        Label:
            创建会话资源
        PreCondition:
            BMC web service normal
        TestStep:
            1) POST https://BMC_IP/redfish/v1/SessionService/Sessions，body里添加{
                        "UserName":"name",   （name实际机器BMC用户名）
                        "Password":"password" （Password实际机器BMC密码）
                        }
        ExpectedResult:
            A) 执行响应码为201,查看新增在线用户信息（与iBMC-用户&安全- 用户信息和创建一致
        Parameters:

        Author:
            baixin liuya
        Last Modified:

        Remark:

    """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.bmc_host = self.device_dut.get_host(host_type=HostType.BMC)
        self.bmc_ip = self.bmc_host.local_ip
        self.bmc_user = self.bmc_host.username
        self.bmc_pwd = self.bmc_host.password

        self.logger.info("获取Token")
        self.request = RequestBase(self.bmc_ip, self.bmc_user, self.bmc_pwd)
        return_code, session_id = self.request.create_session()
        self.assertIsNotNone(return_code)
        self.session_id = session_id

    # 测试步骤
    def procedure(self):
        self.log_step("Step1: 新建用户")
        acc_url = "/redfish/v1/AccountService/Accounts"
        _time_str = datetime.now().strftime("%H%M%S")
        new_user = f"user{_time_str}"
        json_text = {"UserName": f"{new_user}", "Password": "100trust.", "RoleId": "Administrator"}
        resp = self.request.post(url=acc_url, params=json_text)
        rc = resp[0]
        self.assertIsNotNone(rc)
        if rc != 201:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是201，实际返回码{rc}")
        new_user_id = resp[1]['Id']
        self.logger.info(f"新用户{new_user}创建成功")

        url = "/redfish/v1/SessionService/Sessions"
        self.log_step("Step2: 第1次查询会话资源")
        resp = self.request.get(url)
        if resp[0] != 200:
            self.logger.error(json.dumps(resp[1], indent=4, ensure_ascii=False))
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))

        self.log_step("Step3: 创建新会话资源")
        json_text = {"UserName": new_user, "Password": "100trust."}
        resp = self.request.post(url, json_text)
        if resp[0] != 201:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是201，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))

        session_id = resp[1]['Id']

        self.log_step("Step4: 第2次查询会话资源")
        resp = self.request.get(url)
        if resp[0] != 200:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))

        self.log_step("Step5: 删除新建的会话资源")
        resp = self.request.delete(url, session_id)
        if resp[0] != 200:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))

        self.log_step("Step6: 删除新建的用户")
        resp = self.request.delete(acc_url, new_user_id)
        if resp[0] != 200:
            self.logger.error({json.dumps(resp[1], indent=4, ensure_ascii=False)})
            self.assertIsNotNone(None, f"返回码不是200，实际返回码{rc}")
        self.logger.info(json.dumps(resp[1], indent=4, ensure_ascii=False))

    # 测试结束后恢复环境
    def post_test_case(self):
        resp = self.request.delete_session(self.session_id)
        self.assertIsNotNone(resp[0], "清除Token失败")
        self.logger.info("清除Token成功")
